import { useState, useEffect, useMemo } from "react";

// 模拟重型组件，包含大量数据和复杂计算
function HeavyComponent() {
  const [data, setData] = useState([]);
  const [filter, setFilter] = useState('');
  const [sortBy, setSortBy] = useState('name');
  
  useEffect(() => {
    // 生成大量数据
    const generateLargeDataSet = () => {
      const items = [];
      const categories = ['电子产品', '服装', '食品', '图书', '家居', '运动'];
      const brands = ['Apple', 'Samsung', 'Nike', 'Adidas', 'Sony', 'LG', 'Xiaomi', 'Huawei'];
      
      for (let i = 1; i <= 5000; i++) {
        items.push({
          id: i,
          name: `产品 ${i}`,
          brand: brands[Math.floor(Math.random() * brands.length)],
          category: categories[Math.floor(Math.random() * categories.length)],
          price: Math.floor(Math.random() * 10000) + 100,
          rating: (Math.random() * 5).toFixed(1),
          reviews: Math.floor(Math.random() * 1000),
          inStock: Math.random() > 0.2,
          description: `这是产品 ${i} 的详细描述信息，包含了产品的各种特性和功能说明。`,
          features: Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, j) => `特性 ${j + 1}`),
          lastUpdated: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleDateString()
        });
      }
      return items;
    };
    
    // 模拟加载时间
    const timer = setTimeout(() => {
      setData(generateLargeDataSet());
    }, 100);
    
    return () => clearTimeout(timer);
  }, []);
  
  // 昂贵的过滤和排序计算
  const processedData = useMemo(() => {
    console.log('执行重型计算...');
    
    let result = [...data];
    
    // 过滤
    if (filter) {
      result = result.filter(item => 
        item.name.toLowerCase().includes(filter.toLowerCase()) ||
        item.brand.toLowerCase().includes(filter.toLowerCase()) ||
        item.category.toLowerCase().includes(filter.toLowerCase())
      );
    }
    
    // 排序
    result.sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'price':
          return a.price - b.price;
        case 'rating':
          return b.rating - a.rating;
        case 'reviews':
          return b.reviews - a.reviews;
        default:
          return 0;
      }
    });
    
    return result;
  }, [data, filter, sortBy]);
  
  // 统计计算
  const statistics = useMemo(() => {
    if (processedData.length === 0) return { total: 0, avgPrice: 0, inStock: 0 };
    
    const total = processedData.length;
    const avgPrice = processedData.reduce((sum, item) => sum + item.price, 0) / total;
    const inStock = processedData.filter(item => item.inStock).length;
    
    return { total, avgPrice: avgPrice.toFixed(2), inStock };
  }, [processedData]);
  
  return (
    <div className="heavy-component">
      <div className="heavy-header">
        <h3>重型数据组件</h3>
        <p>包含 5000 个产品数据，展示复杂计算和渲染性能</p>
      </div>
      
      <div className="heavy-controls">
        <div className="filter-section">
          <input
            type="text"
            placeholder="搜索产品..."
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="filter-input"
          />
        </div>
        
        <div className="sort-section">
          <label>排序方式:</label>
          <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
            <option value="name">名称</option>
            <option value="price">价格</option>
            <option value="rating">评分</option>
            <option value="reviews">评论数</option>
          </select>
        </div>
      </div>
      
      <div className="statistics">
        <div className="stat-item">
          <span>总产品数:</span>
          <strong>{statistics.total}</strong>
        </div>
        <div className="stat-item">
          <span>平均价格:</span>
          <strong>¥{statistics.avgPrice}</strong>
        </div>
        <div className="stat-item">
          <span>有货:</span>
          <strong>{statistics.inStock}</strong>
        </div>
      </div>
      
      <div className="data-table">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>名称</th>
              <th>品牌</th>
              <th>类别</th>
              <th>价格</th>
              <th>评分</th>
              <th>评论</th>
              <th>库存</th>
              <th>更新时间</th>
            </tr>
          </thead>
          <tbody>
            {processedData.slice(0, 100).map(item => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.brand}</td>
                <td>{item.category}</td>
                <td>¥{item.price}</td>
                <td>⭐ {item.rating}</td>
                <td>{item.reviews}</td>
                <td>{item.inStock ? '✅ 有货' : '❌ 缺货'}</td>
                <td>{item.lastUpdated}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      
      {processedData.length > 100 && (
        <div className="pagination-info">
          <p>显示前 100 条记录，共 {processedData.length} 条</p>
        </div>
      )}
    </div>
  );
}

export default HeavyComponent;